package com.xxq.semester.controller.exam;

import com.xxq.semester.entity.exam.Exams;
import com.xxq.semester.entity.exam.ExamResources;
import com.xxq.semester.entity.exam.ExamQuestions;
import com.xxq.semester.entity.question.Questions;
import com.xxq.semester.entity.ai.AiResources;
import com.xxq.semester.entity.utils.ResponseEntity;
import com.xxq.semester.service.exam.IExamsService;
import com.xxq.semester.service.exam.IExamResourcesService;
import com.xxq.semester.service.exam.IExamQuestionsService;
import com.xxq.semester.service.question.IQuestionsService;
import com.xxq.semester.service.ai.IAiResourcesService;
import com.xxq.semester.service.exam.IStudentAnswersService;
import com.xxq.semester.mapper.StudentExamMapper;
import com.xxq.semester.entity.exam.StudentExam;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

/**
 * 学生端考试控制器
 * 用于学生查看和参加考试
 */
@RestController
@RequestMapping("/api/student/exams")
@Tag(name = "学生考试管理", description = "学生查看和参加考试的相关操作")
public class StudentExamsController {

    @Autowired
    private IExamsService examsService;

    @Autowired
    private IExamResourcesService examResourcesService;

    @Autowired
    private IExamQuestionsService examQuestionsService;

    @Autowired
    private IQuestionsService questionsService;

    @Autowired
    private IAiResourcesService aiResourcesService;

    @Autowired
    private IStudentAnswersService studentAnswersService;

    @Autowired
    private StudentExamMapper studentExamMapper;

    /**
     * 获取某个老师发布的所有考试
     */
    @GetMapping("/teacher/{teacherId}")
    @Operation(summary = "获取老师发布的考试列表", description = "根据老师ID获取所有已发布的考试")
    public ResponseEntity<List<Exams>> getPublishedExamsByTeacher(
            @PathVariable @Parameter(description = "老师ID") Integer teacherId) {
        
        QueryWrapper<Exams> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teacher_id", teacherId)
                   .orderByDesc("created_at");
        
        List<Exams> publishedExams = examsService.list(queryWrapper);
        return ResponseEntity.success(publishedExams);
    }

    /**
     * 获取学生可以参加的所有考试（所有老师发布的考试）
     */
    @GetMapping("/available")
    @Operation(summary = "获取所有可用的考试", description = "获取自己班级的考试（student_exam表，status为空）")
    public ResponseEntity<List<Exams>> getAllAvailableExams(@RequestParam Integer studentId) {
        // 查询student_exam表，筛选status为空的记录
        QueryWrapper<StudentExam> examWrapper = new QueryWrapper<>();
        examWrapper.eq("student_id", studentId).isNull("status");
        List<StudentExam> studentExamList = studentExamMapper.selectList(examWrapper);
        // 根据exam_id查找考试详情
        List<Exams> availableExams = new ArrayList<>();
        for (StudentExam se : studentExamList) {
            Exams exam = examsService.getById(se.getExamId());
            if (exam != null) {
                availableExams.add(exam);
            }
        }
        return ResponseEntity.success(availableExams);
    }

    /**
     * 获取考试详情
     */
    @GetMapping("/{examId}")
    @Operation(summary = "获取考试详情", description = "根据考试ID获取考试详细信息")
    public ResponseEntity<Exams> getExamDetails(
            @PathVariable @Parameter(description = "考试ID") Integer examId) {
        
        Exams exam = examsService.getById(examId);
        if (exam != null && "PUBLISHED".equals(exam.getStatus())) {
            return ResponseEntity.success(exam);
        } else {
            return ResponseEntity.error("考试不存在或未发布");
        }
    }

    /**
     * 获取考试的所有资源
     */
    @GetMapping("/{examId}/resources")
    @Operation(summary = "获取考试资源列表", description = "根据考试ID获取该考试的所有学习资源")
    public ResponseEntity<List<AiResources>> getExamResources(
            @PathVariable @Parameter(description = "考试ID") Integer examId) {

        // 先检查考试是否存在且已发布
        Exams exam = examsService.getById(examId);
        if (exam == null || !"PUBLISHED".equals(exam.getStatus())) {
            return ResponseEntity.error("考试不存在或未发布");
        }

        // 获取考试关联的资源ID列表
        QueryWrapper<ExamResources> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("exam_id", examId);
        List<ExamResources> examResourcesList = examResourcesService.list(queryWrapper);

        // 根据资源ID获取完整的资源信息
        List<AiResources> resourcesList = new ArrayList<>();
        for (ExamResources examResource : examResourcesList) {
            AiResources resource = aiResourcesService.getById(examResource.getResourceId());
            if (resource != null) {
                resourcesList.add(resource);
            }
        }

        return ResponseEntity.success(resourcesList);
    }

    /**
     * 获取考试的所有题目
     */
    @GetMapping("/{examId}/questions")
    @Operation(summary = "获取考试题目列表", description = "根据考试ID获取该考试的所有题目")
    public ResponseEntity<List<Questions>> getExamQuestions(
            @PathVariable @Parameter(description = "考试ID") Integer examId) {

        // 先检查考试是否存在且已发布
        Exams exam = examsService.getById(examId);
        if (exam == null || !"PUBLISHED".equals(exam.getStatus())) {
            return ResponseEntity.error("考试不存在或未发布");
        }

        // 获取考试关联的题目ID列表
        QueryWrapper<ExamQuestions> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("exam_id", examId);
        List<ExamQuestions> examQuestionsList = examQuestionsService.list(queryWrapper);        // 根据题目ID获取完整的题目信息
        List<Questions> questionsList = new ArrayList<>();
        for (ExamQuestions examQuestion : examQuestionsList) {
            Questions question = questionsService.selectQuestionsByQuestionId(examQuestion.getQuestionId());
            if (question != null) {
                questionsList.add(question);
            }
        }

        return ResponseEntity.success(questionsList);
    }

    /**
     * 获取考试的完整信息（包括题目和资源）
     */
    @GetMapping("/{examId}/details")
    @Operation(summary = "获取考试完整信息", description = "获取考试详情、题目列表和资源列表")
    public ResponseEntity<Map<String, Object>> getExamFullDetails(
            @PathVariable @Parameter(description = "考试ID") Integer examId) {

        // 检查考试是否存在且已发布
        Exams exam = examsService.getById(examId);
        if (exam == null || !"PUBLISHED".equals(exam.getStatus())) {
            return ResponseEntity.error("考试不存在或未发布");
        }

        // 获取题目列表
        QueryWrapper<ExamQuestions> questionQueryWrapper = new QueryWrapper<>();
        questionQueryWrapper.eq("exam_id", examId);
        List<ExamQuestions> examQuestionsList = examQuestionsService.list(questionQueryWrapper);        List<Questions> questionsList = new ArrayList<>();
        for (ExamQuestions examQuestion : examQuestionsList) {
            Questions question = questionsService.selectQuestionsByQuestionId(examQuestion.getQuestionId());
            if (question != null) {
                questionsList.add(question);
            }
        }

        // 获取资源列表
        QueryWrapper<ExamResources> resourceQueryWrapper = new QueryWrapper<>();
        resourceQueryWrapper.eq("exam_id", examId);
        List<ExamResources> examResourcesList = examResourcesService.list(resourceQueryWrapper);

        List<AiResources> resourcesList = new ArrayList<>();
        for (ExamResources examResource : examResourcesList) {
            AiResources resource = aiResourcesService.getById(examResource.getResourceId());
            if (resource != null) {
                resourcesList.add(resource);
            }
        }

        // 组装返回数据
        Map<String, Object> response = new HashMap<>();
        response.put("exam", exam);
        response.put("questions", questionsList);
        response.put("resources", resourcesList);
        response.put("questionCount", questionsList.size());
        response.put("resourceCount", resourcesList.size());

        return ResponseEntity.success(response);
    }

    /**
     * 开始考试（简单的考试开始确认）
     */
    @PostMapping("/{examId}/start")
    @Operation(summary = "开始考试", description = "学生开始参加考试")
    public ResponseEntity<Map<String, Object>> startExam(
            @PathVariable @Parameter(description = "考试ID") Integer examId,
            @RequestParam @Parameter(description = "学生ID") Integer studentId) {

        // 检查考试是否存在且已发布
        Exams exam = examsService.getById(examId);
        if (exam == null || !"PUBLISHED".equals(exam.getStatus())) {
            return ResponseEntity.error("考试不存在或未发布");
        }

        // 获取考试的题目数量
        QueryWrapper<ExamQuestions> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("exam_id", examId);
        List<ExamQuestions> examQuestionsList = examQuestionsService.list(queryWrapper);

        Map<String, Object> response = new HashMap<>();
        response.put("examId", examId);
        response.put("studentId", studentId);
        response.put("message", "考试开始成功");
        response.put("questionCount", examQuestionsList.size());
        response.put("startTime", System.currentTimeMillis());

        return ResponseEntity.success(response);
    }

}
